import com.sun.org.apache.xml.internal.security.utils.HelperNodeList;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-05-22
 * Time: 23:35
 */
public class TestHeap {
    public int[] elem;
    public int usedSize;
    public TestHeap(){
        this.elem = new int[10];
    }
    public void initElem(int[] array){
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }
    public void createBigHeap(){
        for (int parent = (usedSize-1-1)/2; parent >=0 ; parent--) {
            siftDown(parent, usedSize);
        }
    }
    private void siftDown(int parent , int len){
        int child = parent*2 +1;
        while(child < len){
            if(child+1 < len && elem[child] < elem[child+1]){
             child++;
              }
            if(elem[parent] < elem[child]){
                swap(parent,child);
                parent = child;
                child = parent*2 +1;
            }else{
                break;
            }

        }

    }

    /**
     * 堆的删除
     * @return
     */
    public int poll(){
        int val = elem[0];
        swap(0,usedSize-1);
        usedSize--;
        siftDown(0,usedSize);
        return val;
    }

    private void swap(int parent, int child) {
        int tmp =elem[parent];
        elem[parent] = elem[child];
        elem[child] = tmp;
    }
}
